﻿using Mapster;
using RuoVea.ExDto;
using SqlSugar;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RuoVea.ExSugar;

/// <summary>
/// 分页扩展
/// </summary>
public static partial class PagedExtensions
{
    /// <summary>
    /// 分页
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <param name="isMapper"></param>
    /// <returns></returns>
    public static async Task<PageResult<T>> ToPageAsync<T>(this ISugarQueryable<T> query, int pageIndex, int pageSize, bool isMapper = true)
    {
        RefAsync<int> total = 0;
        var items = await query.ToPageListAsync(pageIndex, pageSize, total);
        return new PageResult<T>(pageIndex, pageSize)
        {
            Rows = isMapper ? items.Adapt<List<T>>() : items,
            TotalRows = total,
        };
    }
    /// <summary>
    /// 分页
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="Dto"></typeparam>
    /// <param name="query"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public static async Task<PageResult<Dto>> ToPageAsync<T, Dto>(this ISugarQueryable<T> query, int pageIndex, int pageSize)
    {
        RefAsync<int> total = 0;
        var items = await query.ToPageListAsync(pageIndex, pageSize, total);
        return new PageResult<Dto>(pageIndex, pageSize)
        {
            Rows = items.Adapt<List<Dto>>(),
            TotalRows = total,
        };
    }

    /// <summary>
    /// 分页
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <typeparam name="Dto"></typeparam>
    /// <param name="query"></param>
    /// <param name="pageParam"></param>
    /// <returns></returns>
    public static async Task<PageResult<Dto>> ToPageAsync<T, Dto>(this ISugarQueryable<T> query, PageParam pageParam)
    {
        RefAsync<int> total = 0;
        var items = await query.ToPageListAsync(pageParam.PageNo, pageParam.PageSize, total);
        return new PageResult<Dto>(pageParam.PageNo, pageParam.PageSize)
        {
            Rows = items.Adapt<List<Dto>>(),
            TotalRows = total,
        };
    }

}

